<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" :title="`${operationType}百业信息`">
        发布、修改百业信息，如果是平台发布的信息，则自动与录入人员关联并设置为已审核状态。平台发布的信息，一旦提交默认都是为发布状态，在网页、小程序、App端都可以查看到。(系统用户、系统管理员共用一张用户表)
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-3 proCard">
      <n-grid cols="1 s:1 m:2 l:2 xl:4 2xl:4" responsive="screen">
        <n-grid-item offset="0 s:0 m:0 l:0 xl:1 2xl:0" span="0 s:1 m:2 l:2 xl:2 2xl:2">
          <n-form
            ref="formRef"
            :label-width="80"
            :model="formValue"
            :rules="rules"
            class="py-8"
            label-placement="left"
          >
            <n-form-item label="信息分类" path="category_id">
              <n-tree-select
                key-field="id"
                label-field="name"
                :options="categoryTree"
                clearable
                v-model:value="formValue.category_id"
              />
            </n-form-item>
            <n-form-item label="信息标题" path="title">
              <n-input v-model:value="formValue.title" placeholder="请输入一个吸引人的标题" />
            </n-form-item>
            <n-form-item label="信息详情" path="description">
              <n-input
                v-model:value="formValue.description"
                placeholder="请输入要发布的内容(详情)"
                type="textarea"
                :autosize="{
                  minRows: 5,
                  maxRows: 10,
                }"
              />
            </n-form-item>
            <n-form-item label="信息图片" path="img">
              <BasicUpload
                v-model:value="formValue.images"
                :action="`${uploadUrl}/api/images`"
                :data="{ type: '0' }"
                :headers="uploadHeaders"
                :height="100"
                :width="100"
                :maxSize="9"
                name="image"
                helpText="单个文件不超过20MB，最多只能上传9个文件"
                @uploadChange="uploadChange"
              />
            </n-form-item>
            <n-form-item label="联系人" path="contact">
              <n-input
                v-model:value="formValue.contact"
                placeholder="请输入联系人称呼，例如:苟先生"
              />
            </n-form-item>
            <n-form-item label="联系电话" path="phone">
              <n-input v-model:value="formValue.phone" placeholder="电话号码" />
            </n-form-item>
            <n-form-item label="联系地址" path="address">
              <n-input v-model:value="formValue.address" placeholder="请输入地址" />
            </n-form-item>
            <n-form-item label="经纬度" path="location">
              <n-input
                type="text"
                placeholder="经度"
                disabled
                v-model:value="longitudeStrValue"
                style="width: 45%"
              />
              <n-input
                type="text"
                placeholder="纬度"
                disabled
                v-model:value="latitudeStrValue"
                style="width: 45%; margin-left: 80px"
              />
            </n-form-item>
            <n-form-item label="模糊搜索" path="location">
              <el-autocomplete
                v-model="address"
                :fetch-suggestions="querySearch"
                placeholder="请输入详细地址"
                :trigger-on-focus="false"
                style="width: 100%"
                @select="placeSelected"
              />
            </n-form-item>
            <n-form-item label="定位" path="latlng">
              <div class="map" ref="txMapRef" style="height: 250px; width: 100%"></div
            ></n-form-item>
            <div style="margin-left: 80px">
              <n-space>
                <n-button type="primary" @click="formSubmit">提交发布</n-button>
                <n-button @click="resetForm">重置</n-button>
              </n-space>
            </div>
          </n-form>
        </n-grid-item>
      </n-grid>
    </n-card>
  </div>
</template>

<script lang="ts">
  export default {
    name: 'BasicForm',
  };
</script>
<script lang="ts" setup>
  import { ref, unref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useMessage, FormRules, FormItemRule } from 'naive-ui';
  import { BasicUpload } from '@/components/Upload';
  import { useGlobSetting } from '@/hooks/setting';
  import {
    addInformation,
    editInformation,
    getInformation,
    informationCategoryTree,
  } from '@/api/information/information';
  import { keywordSearch, addressResolution } from '@/api/system/map';
  import { useTabs } from '@/hooks/web/useTags';

  const { closeCurrent } = useTabs();
  // 通过route，获取页面提交过来的参数
  const route = useRoute();
  const router = useRouter();
  const operationType = ref('新增');
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;

  const rules: FormRules = {
    category_id: {
      required: true,
      message: '请选择所属分类',
    },
    title: {
      required: true,
      message: '请输入信息标题',
      trigger: 'blur',
    },
    description: {
      required: true,
      message: '请输入要发布的内容',
      trigger: ['input'],
    },
    phone: [
      {
        required: true,
        message: '请输入预约备注',
        trigger: 'blur',
      },
      {
        validator: validatePhoneNumber,
        message: '输入手机号码不正确',
        trigger: 'blur',
      },
    ],
  };

  const formRef: any = ref(null);
  const categoryTree = ref([]);
  const message = useMessage();

  const defaultValueRef = (): {
    id: null | number;
    category_id: null | number;
    title: string;
    description: string;
    contact: string;
    phone: string;
    images: string[];
    address: string;
    longitude: null | number;
    latitude: null | number;
  } => ({
    id: null,
    category_id: null,
    title: '',
    description: '',
    contact: '',
    phone: '',
    images: [],
    address: '',
    longitude: 98.577218279242525,
    latitude: 24.44100787549681,
  });

  // 需要提交的表单
  let formValue = reactive(defaultValueRef());
  const uploadHeaders: any = reactive({
    platform: 'admin',
    timestamp: new Date().getTime(),
  });

  // 使用计算属性来处理类型转换
  const longitudeStrValue = computed({
    get: () => (formValue.longitude ? formValue.longitude.toString() : null),
    set: () => (formValue.longitude ? formValue.longitude.toString() : null),
  });
  const latitudeStrValue = computed({
    get: () => (formValue.latitude ? formValue.latitude.toString() : null),
    set: () => (formValue.latitude ? formValue.latitude.toString() : null),
  });

  // 腾讯地图
  const address = ref('');
  const TMap = (window as any).TMap;
  let txMap: any;
  let marker: any;
  //初始化地图
  const initMap = () => {
    let center: any;
    if (formValue.longitude) {
      // 如果信息设置了坐标，就使用信息的坐标作为地图中心
      center = new TMap.LatLng(Number(formValue.latitude), Number(formValue.longitude));
    } else {
      // 如果信息没有设置坐标，就使用默认的坐标作为地图中心
      center = new TMap.LatLng(24.440917645248334, 98.5777526658037);
    }
    // formParams.value.latitude = center.lat;
    // formParams.value.longitude = center.lng;
    txMap = new TMap.Map(txMapRef.value, {
      center: center, //设置地图中心点坐标
      zoom: 15, //设置地图缩放级别
      viewMode: '2D',
    });
    txMap.addListener('dblclick', function (event) {
      formValue.latitude = event.latLng.getLat();
      formValue.longitude = event.latLng.getLng();
      if (marker) {
        // 更新标记位置
        var data = marker.getGeometryById('marker');
        Object.assign(data, {
          position: new TMap.LatLng(formValue.latitude, formValue.longitude),
        });
        marker.updateGeometries([data]);
      } else {
        addMarker();
      }
    });
    // 是否需要添加标记
    if (formValue.longitude) {
      addMarker();
    }
  };
  function addMarker() {
    marker = new TMap.MultiMarker({
      map: txMap,
      styles: {
        // 点标记样式
        marker: new TMap.MarkerStyle({
          width: 20, // 样式宽
          height: 30, // 样式高
          anchor: { x: 10, y: 30 }, // 描点位置
        }),
      },
      geometries: [
        // 点标记数据数组
        {
          // 标记位置(纬度，经度，高度)
          id: 'marker', //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
          position: new TMap.LatLng(formValue.latitude, formValue.longitude), //点标记坐标位置
        },
      ],
    });
  }
  //搜索
  const querySearch = async (queryString: string, cb: any): Promise<any> => {
    try {
      let params = {
        keyword: queryString,
        key: 'EL6BZ-LCWWJ-727FZ-F3HGA-XSS4O-S4BPQ',
      };
      let res = await keywordSearch(params);
      let { data } = res;
      const results = data.data.map((item: any) => {
        let obj = {
          value: item.address,
          address: item.address,
        };
        return obj;
      });
      cb(results);
    } catch (e) {
      console.log(e);
    }
  };
  async function placeSelected(location) {
    let params = {
      address: location.address,
      key: 'EL6BZ-LCWWJ-727FZ-F3HGA-XSS4O-S4BPQ',
    };
    let res = await addressResolution(params);
    let { result } = res.data;
    txMap.setCenter(new TMap.LatLng(result.location.lat, result.location.lng));
  }
  const txMapRef = ref(null);

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        if (!formValue.id) {
          // 新增信息
          addInformation(formValue)
            .then(() => {
              message.success('保存成功!');
              closeCurrent();
              router.push({ name: 'information_list' });
            })
            .catch(() => {
              message.error('保存失败!');
            });
        } else {
          // 修改信息
          editInformation(formValue)
            .then(() => {
              message.success('保存成功!');
              closeCurrent();
              // 跳转到list页面
              router.push({ name: 'information_list' });
            })
            .catch(() => {
              message.error('保存失败!');
            });
        }
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  function resetForm() {
    formRef.value.restoreValidation();
    formValue = Object.assign(unref(formValue), defaultValueRef());
  }

  function uploadChange(list: string[]) {
    formValue.images = list;
  }

  function validatePhoneNumber(rule: FormItemRule, value: string): boolean {
    const phoneRegex = /^1[3-9]\d{9}$/; // 示例: 简单的中国大陆手机号码正则表达式
    if (phoneRegex.test(value)) {
      return true;
    } else {
      return false;
    }
  }

  async function getInformationCategory() {
    const cateTree = await informationCategoryTree();
    categoryTree.value = cateTree;
  }

  async function loadInformation(id) {
    const information = await getInformation(id);
    // 将获取到的information赋值给formValue
    Object.keys(information).forEach((key) => {
      if (formValue.hasOwnProperty(key)) {
        formValue[key] = information[key];
      }
    });
    // 将地图移动到中心
    txMap.setCenter(new TMap.LatLng(formValue.latitude, formValue.longitude));
    addMarker();
  }

  onMounted(() => {
    initMap();
    // 加载分类树形结构
    getInformationCategory();
    // 如果打开页面有params.id参数，那么就查询相应的百业信息
    if (route.query.id) {
      loadInformation(route.query.id);
      operationType.value = '修改';
    }
  });
</script>
